package com.wedo.mall.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.e.library.fragment.EFragment;
import com.wedo.mall.R;
import com.wedo.mall.activity.comment.ImageActivity;
import com.wedo.mall.util.WUrl;

import butterknife.BindView;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * Created by e on 2017/10/15.
 */

public class ImageFragment extends EFragment<ImageActivity>{

    @BindView(R.id.pv_photo) PhotoView pv_photo;
    @BindView(R.id.pb_loading) ProgressBar pb_loading;

    public static ImageFragment with(String imageUrl) {
        ImageFragment fragment = new ImageFragment();
        Bundle args = new Bundle();
        args.putString("url", imageUrl);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int layout() {
        return R.layout.fragment_image;
    }

    @Override
    protected void onFragmentCreated(View contentView, Bundle bundle) {
        pv_photo.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
            @Override
            public void onPhotoTap(View view, float x, float y) {
                activity().defaultFinish();
            }
        });

        pb_loading.setVisibility(View.VISIBLE);
        String url = getArguments() != null ? getArguments().getString("url") : null;
        String img = WUrl.url(url);
        Glide.with(this).load(img).error(R.drawable.place_holder_goods).placeholder(R.drawable.place_holder_goods)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String s, Target<GlideDrawable> target, boolean b) {

                        activity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                pb_loading.setVisibility(View.GONE);
                                activity().toast(getString(R.string.imageCantShow));
                            }
                        });
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable glideDrawable, String s, Target<GlideDrawable> target, boolean b, boolean b1) {
                        pb_loading.setVisibility(View.GONE);
                        return false;
                    }
                }).into(pv_photo);

    }
}
